package com.trinity.sample.view.foucs

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout

import java.util.HashMap

class MarkerLayout : FrameLayout {

  @SuppressLint("UseSparseArrays")
  private val mViews = HashMap<Int, View>()

  constructor(context: Context) : super(context)

  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

  constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

  /**
   * 添加一个触摸marker点
   */
  fun onMarker(type: Int, marker: AutoFocusMarker?) {

    val oldView = mViews[type]

    if (oldView != null) {
      removeView(oldView)
    }
    if (marker == null) {
      return
    }

    val newView = marker.onAttach(context, this)
    if (newView != null) {
      mViews[type] = newView
      addView(newView)
    }
  }


  fun onEvent(type: Int, point: PointF) {
    val view = mViews[type] ?: return
    view.clearAnimation()

    if (type == TYPE_AUTOFOCUS) {
      // view 是marker ，而不是MarkerLayout 。
      val x = (point.x - view.width / 2)
      val y = (point.y - view.height / 2)

      view.translationX = x
      view.translationY = y
    }
  }

  companion object {
    const val TYPE_AUTOFOCUS = 1
  }
}
